package org.compiere.process;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.compiere.model.X_cms_agreement;
import org.compiere.util.DB;

public class cms_isapproved extends SvrProcess {

	/** Current context					*/
	//private Properties m_ctx;
	/**	 */
	//private ProcessInfo pi;
	/** */
	private X_cms_agreement agreement;
	
	//private int p_AD_User_ID = 0;
	
	@Override
	protected void prepare() {
		log.info("");
		//m_ctx = Env.getCtx();
		//pi = getProcessInfo();
		
		agreement = new X_cms_agreement(getCtx(), getRecord_ID(), get_TrxName());
	 	//p_AD_User_ID = Env.getAD_User_ID(getCtx());
	}

	@SuppressWarnings("resource")
	@Override
	protected String doIt() throws Exception 
	{
		if(agreement.isProcessed() || agreement.isProcessing())
		{
			return "Процесс был уже согласован";
		}
		
		String sql = "Select cms_statusestype_id from adempiere.cms_statusestype where lower(name) like '%подписан%'";
		int cms_status_id = DB.getSQLValue(get_TrxName(), sql);
		
		if(cms_status_id == -1)
			return ("Договор не возможно перевести в статус \"Подписан\"");
		
		sql = "select cms_statusestype_id from adempiere.cms_contract where cms_contract_id = " + agreement.getCMS_Contract_ID();
		int cms_statusToCompare = DB.getSQLValue(get_TrxName(), sql);
		
		if(cms_statusToCompare == cms_status_id)
			return("Договор уже подписан");
		
		sql = "SELECT cms_agreement_line_id, sign_y, sign_n from adempiere.cms_agreement_line where cms_agreement_id = " + agreement.get_ID();
		
		PreparedStatement pstmt = null;
		ResultSet rs = null;		
		
		boolean isProcessed = true;
		int count = 0;
		
		//int cms_agreementline_id = 0;
		
		try
		{
			pstmt = DB.prepareStatement(sql, get_TrxName());
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				if(rs.getString("sign_y") == null && rs.getString("sign_n") == null)
				{
					throw new Exception("Согласование не может быть выполненно");
				}
				if(rs.getString("sign_y").compareTo("N") == 0)
				{
					isProcessed = false;
					//cms_agreementline_id = rs.getInt("cms_agreement_line_id");
				}
				count++;
			}
		}
		catch(Exception e) {}
		finally 
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
		if(count != 0)
		{	
//			agreement.setProcessed(false);
//			agreement.setProcessing(true);
//			if(!agreement.save())
//				throw new Exception("Не удалось выполнить процесс");
		}
		
		if(isProcessed && count > 0)
		{
//			X_CMS_Contract contract = new X_CMS_Contract(getCtx(), agreement.getCMS_Contract_ID(), get_TrxName());		
			//contract.setcms_statusestype_ID(X_cms_statusestype.CMS_Signed);
		
			//if(!contract.save())
			//	throw new Exception("Не удалось выполнить процесс");
		}
		
		return null;
	}

}
